package com.suanfa.node;

import org.w3c.dom.NodeList;

/**
 * 指定区间的链表反转
 */
public class RangeNodeReverse {
    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        //ListNode listNode3 = new ListNode(3);
        //ListNode listNode4 = new ListNode(4);
        //ListNode listNode5 = new ListNode(5);
        //NodeSingle nodeSingle6 = new NodeSingle(6);
        listNode1.next = listNode2;
        //listNode2.next = listNode3;
        //listNode3.next = listNode4;
        //listNode4.next = listNode5;
        //nodeSingle5.next = nodeSingle6;

        ListNode single = parse(listNode1,1,2);

        while(single != null){
            System.out.println(single.value);
            single = single.next;
        }

    }

    public static ListNode parse(ListNode head, int left, int right){
        if(left == right){
            return head;
        }
        ListNode temp = new ListNode(-1);
        temp.next = head;
        ListNode leftNode = temp;
        for(int i = 0; i < left - 1; i++){
            leftNode = leftNode.next;
        }

        ListNode startNode = leftNode.next;
        ListNode pre = null;
        ListNode next = null;
        ListNode reverse = startNode;
        for(int i=0; i <= right - left; i++){
            next = reverse.next;
            reverse.next = pre;
            pre = reverse;
            reverse = next;
        }
        leftNode.next = pre;
        startNode.next = reverse;
        return temp.next;

    }



    public static ListNode reverse(ListNode head){
        if(head == null ){//当前是最后一个节点
            return null;
        }
        ListNode pre = null;
        ListNode current = head;
        ListNode next = null;

        while(current != null){
            next = current.next;
            current.next = pre;
            pre = current;
            current = next;
        }
        return pre;
    }
}
